package com.wuyou.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.wuyou.domain.Result;
import com.wuyou.em.ResultEnum;
import com.wuyou.entity.RentOrder;
import com.wuyou.service.IRentOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 张钧程
 * @since 2022-09-30
 */
@RestController
@RequestMapping("rentOrder")
public class RentOrderController {

    @Autowired
    private IRentOrderService os;

    //查询所有租金账单
    @GetMapping
    public Result getRentOrder(){
        List<RentOrder> list = os.list();
        if (list.isEmpty()){
            return Result.ERROR();
        }
        return Result.OK().setData(list);
    }

    //增加租金账单
    @PostMapping
    public Result addRentOrder(RentOrder rentOrder){
        if(BeanUtil.isEmpty(rentOrder)){
            return Result.R(ResultEnum.MESSAGE_ERROR);
        }
        if(rentOrder.getHostPhone().length() != 11 || rentOrder.getUserPhone().length() != 11){
            return Result.R(ResultEnum.PHONE_ERROR);
        }
        String s = RandomUtil.randomNumbers(19);
        rentOrder.setRentOrderId(Long.valueOf(s));
        rentOrder.setPayTime(new Date());
        rentOrder.setLastPayTime(new Date());

        boolean save = os.save(rentOrder);
        if(save){
            return Result.OK();
        }else{
            return Result.ERROR();
        }
    }

    //修改指定的租金账单
    @PutMapping
    public Result updateRent(RentOrder rentOrder){
        if(BeanUtil.isEmpty(rentOrder)){
            return Result.R(ResultEnum.MESSAGE_ERROR);
        }
        if(rentOrder.getHostPhone().length() != 11 || rentOrder.getUserPhone().length() != 11){
            return Result.R(ResultEnum.PHONE_ERROR);
        }

        boolean b = os.updateById(rentOrder);
        if(b){
            return Result.OK();
        }else{
            return Result.ERROR();
        }
    }

    //删除指定的账单数据
    @DeleteMapping
    public Result deleteRent(Long rentId){
        boolean remove = os.removeById(rentId);
        if (remove){
            return Result.OK();
        }else{
            return Result.ERROR();
        }
    }


}
